package org.learning;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;

/**
 * CountDownLatch的演示案例
 * 妈妈等3个孩子吃完饭去洗碗。
 */
public class A_22 {
    static class Child extends Thread {
        private final CountDownLatch countDownLatch;
        private final Random random = new Random();

        public Child(String name, CountDownLatch countDownLatch) {
            super(name);
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "开始吃饭了。。");
            try {
                Thread.sleep(random.nextInt(10_000));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "吃完饭了。。");
            countDownLatch.countDown();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("妈妈做好饭了。。。");
        //CountDownLatch不分公平与非公平的实现，默认是放到队列中也就是公平的。
        CountDownLatch countDownLatch = new CountDownLatch(3);
        IntStream.range(0, 3)
                .mapToObj(v -> new Child("小孩" + v, countDownLatch))
                .forEach(Thread::start);
        countDownLatch.await();
        System.out.println("小孩都吃完饭了，妈妈开始洗碗收拾。。。");
    }
}
